package fun.chutianshu.eescore_09_shiro1.shiro;

import com.alibaba.druid.util.StringUtils;
import fun.chutianshu.eescore_09_shiro1.entity.Permission;
import fun.chutianshu.eescore_09_shiro1.entity.Role;
import fun.chutianshu.eescore_09_shiro1.entity.UserInfo;
import fun.chutianshu.eescore_09_shiro1.mappers.PermissionMapper;
import fun.chutianshu.eescore_09_shiro1.mappers.RoleMapper;
import fun.chutianshu.eescore_09_shiro1.mappers.UserInfoMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

public class MyRealm extends AuthorizingRealm {
    @Autowired
    UserInfoMapper userInfoMapper;
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    PermissionMapper permissionMapper;

    //此方法用来鉴权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取登录用户名
        String user_name = (String) principalCollection.getPrimaryPrincipal();
        //查询用户名称
        UserInfo user = userInfoMapper.findByName(user_name);
        //添加角色和权限
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        for (Role role : roleMapper.getAll()) {
            //添加角色
            simpleAuthorizationInfo.addRole(role.getRole_name());
            //添加权限
            for (Permission permission : role.getPermissions()) {
                simpleAuthorizationInfo.addStringPermission(permission.getPermissionsName());
            }
        }
        return simpleAuthorizationInfo;
    }
    //此方法用来验证登录
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        if (StringUtils.isEmpty((String) token.getPrincipal())) {
            return null;
        }
        String username = (String) token.getPrincipal();
        if (!"xyz".equals(username)) {
            throw new UnknownAccountException("账户不存在!");
        }
        return new SimpleAuthenticationInfo(username, "123", getName());
    }

}
